package xcoupon

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/optional/xnsq"
	"gitee.com/xiaoyutab/xgotool/xerror"
	"gitee.com/xiaoyutab/xgotool/xnum"
)

// 创建优惠券详情
// PS: 优惠批次Used、优惠券类型Type、优惠券平台Platform不允许修改
//
//	c	优惠券详情
func Create(c *Coupon) error {
	if c.Uid == 0 {
		return xerror.New("优惠券创建人不能为空")
	}
	// 禁止修改的选项覆盖
	if c.Id > 0 {
		old, err := Info(c.Id)
		if err != nil {
			return err
		}
		c.CreatedAt = old.CreatedAt
		c.Platform = old.Platform
		c.Used = old.Used
		c.Type = old.Type
		if c.Examine == 3 {
			// 一旦审核通过将不能再修改其内容，仅允许修改status状态
			old.Status = c.Status
			if c.ChildOver != 0 {
				old.ChildOver = c.ChildOver
			}
			c = old
		}
	}
	// 类型判断
	if !xnum.InArray(c.Type, coupon_type) {
		return xerror.New("优惠券类型选择错误，目前仅支持1-4、11-14八种类型")
	}
	// 批次效验
	if c.Used > 0 {
		//	批次共用券
		_, err := UsedInfo(c.Used)
		if err != nil {
			return err
		}
	}
	// 平台效验
	if c.Platform == 0 {
		return xerror.New("所属平台不能为空")
	}
	_, err := PlatformInfo(c.Platform)
	if err != nil {
		return err
	}
	if !xnum.InArray(c.AvtivationStatus, []uint8{0, 1}) {
		return xerror.New("优惠券发放方式选择错误")
	}
	if c.WithAmount < 0 {
		return xerror.New("满x金额不允许为负数")
	}
	if c.UsedAmount <= 0 {
		return xerror.New("减x金额不允许为零且不允许为负数")
	}
	if c.Quota == 0 {
		return xerror.New("发券数量禁止为0")
	}
	if !xnum.InArray(c.StartType, []uint8{1, 2}) {
		return xerror.New("发券时间类型选择错误")
	}
	if !xnum.InArray(c.ValidType, []uint8{1, 2}) {
		return xerror.New("领券时效选择错误")
	}
	if !xnum.InArray(c.Status, []uint8{1, 2, 3}) {
		return xerror.New("券状态传输错误")
	}
	if !xnum.InArray(c.ChildOver, []uint8{0, 1, 2}) {
		return xerror.New("子券状态传输错误")
	}
	if !xnum.InArray(c.Examine, []uint8{0, 1, 2, 3, 4}) {
		return xerror.New("券审核状态传输错误")
	}
	c.UpdatedAt = time.Now().Format(time.DateTime)
	if c.CreatedAt == "" {
		c.CreatedAt = c.UpdatedAt
	}
	// 进行数据存储
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	// 时间字段格式化，避免存储异常
	if c.StartTime == "" {
		c.StartTime = c.UpdatedAt
	}
	if c.EndTime == "" {
		c.EndTime = "2099-12-31 23:59:59"
	}
	if c.ValidStartTime == "" {
		c.ValidStartTime = c.UpdatedAt
	}
	if c.ValidEndTime == "" {
		c.ValidEndTime = "2099-12-31 23:59:59"
	}
	err = _default.DB.Table(_default.CouponTable).Save(c).Error
	if err != nil {
		return xlog.AE("优惠券信息存储错误", err)
	}
	// 缓存更新
	xcache.SetStruct(xcache.Key("xgotool.xcoupon.info", c.Id), c)
	if c.Examine == 3 && c.ChildOver == 0 {
		// 队列发送子券
		xnsq.Set("xcoupon.child.create", c)
	}
	return nil
}
